package com.adcc.ags.msgStore.managed;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.routing.FromConfig;
import com.adcc.ags.msgStore.service.MsgStoreInDBServiceImpl;
import com.adcc.ags.msgStore.service.MsgStoreInFileServiceImpl;
import com.adcc.utility.log.Log;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Environment;

/**
 * 报文代理Managed
 */
public class MsgProxy implements Managed {

    // 单例对象
    private static MsgProxy instance;

    // 配置文件
    private String proxyConf;

    // ActorSystem mailbox
    private ActorSystem mailBoxActorSys;

    // ActorSystem router
    private ActorSystem routerActorSys;

    // Actor
    private ActorRef msgStoreInDBActor;

    // 告警触发器
    private ActorRef msgStoreInFileActor;

    /**
     * 构造方法
     * */
    private MsgProxy() {}

    /**
     * 单例模式
     * */
    public synchronized static MsgProxy getInstance() {
        if (instance == null) {
            instance = new MsgProxy();
        }
        return instance;
    }

    public void setProxyConf(String proxyConf) {
        this.proxyConf = proxyConf;
    }

    public ActorRef getMsgStoreInDBActor() {
        return msgStoreInDBActor;
    }

    public ActorRef getMsgStoreInFileActor() {
        return msgStoreInFileActor;
    }

    public void build(Environment environment) throws Exception{
        environment.lifecycle().manage(this);
    }

    public void build(Environment environment, String proxyConf) throws Exception{
        this.proxyConf = proxyConf;
        environment.lifecycle().manage(this);
    }

    @Override
    public void start() throws Exception {
        try {
            // 初始化Actor
            Config config = ConfigFactory.load(proxyConf);
            routerActorSys = ActorSystem.create("routerActor", config);
            mailBoxActorSys = ActorSystem.create("mailBoxActor",config.getConfig("akka").getConfig("actor"));
            msgStoreInDBActor = mailBoxActorSys.actorOf(Props.create(MsgStoreInDBServiceImpl.class).withMailbox("storage-mailbox"),"msgStoreInDB");
            msgStoreInFileActor = routerActorSys.actorOf(Props.create(MsgStoreInFileServiceImpl.class).withRouter(new FromConfig()), "msgStoreInFile");
        } catch (Exception ex) {
            Log.error(MsgProxy.class.getName(), "start() error", ex);
        }
    }

    @Override
    public void stop() throws Exception {
        try {
            if (mailBoxActorSys != null) {
                mailBoxActorSys.shutdown();
            }
            if (routerActorSys != null) {
                routerActorSys.shutdown();
            }
        } catch (Exception ex) {
            Log.error(MsgProxy.class.getName(), "stop() error", ex);
        }
    }
}
